//
//  LBOCPayManager.m
//  Expecta
//
//  Created by 苗治会 on 2020/2/25.
//

#import "LBOCPayManager.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import <LBOCPay/UPPaymentControl.h>

#ifdef DEBUG
    #define unionMode @"01"
#else
    #define unionMode @"00"
#endif

@interface LBOCPayManager ()<WXApiDelegate>

@property(nonatomic, copy) CompleteCallBack callBack;

@property(nonatomic, strong) NSMutableDictionary *appSchemeDic;

@end

@implementation LBOCPayManager

+ (instancetype)shareManager {
    static LBOCPayManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)registerApp {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *urlTypes = dic[@"CFBundleURLTypes"];
    for (NSDictionary *urlTypeDic in urlTypes) {
        NSString *urlName = urlTypeDic[@"CFBundleURLName"];
        NSArray *urlSchemes = urlTypeDic[@"CFBundleURLSchemes"];
        // 一般对应只有一个
        NSString *urlScheme = urlSchemes.lastObject;
        if ([urlName isEqualToString:WEIXINPAYFLAG]) {
            [self.appSchemeDic setValue:urlScheme forKey:WEIXINPAYFLAG];
            // 注册微信
            [WXApi registerApp:urlScheme];
        } else if ([urlName isEqualToString:ALIPAYFLAG]) {
            [self.appSchemeDic setValue:urlScheme forKey:ALIPAYFLAG];
        } else if ([urlName isEqualToString:UNIONPAYFLAG]) {
            [self.appSchemeDic setValue:urlScheme forKey:UNIONPAYFLAG];
        }
    }
}

- (void)payWithType:(PayType)payType orderMessage:(id)orderMessage viewController:(UIViewController *)sourceVC callBack:(CompleteCallBack)callBack {
    self.callBack = callBack;
    if (payType == PayTypeWX) {
        BOOL flag = [WXApi sendReq:(PayReq *)orderMessage];
        if (!flag) {
            if (self.callBack) {
                self.callBack(PayResultFailure, @"微信发送支付请求失败");
            }
        }
    } else if (payType == PayTypeAli) {
        [[AlipaySDK defaultService] payOrder:(NSString *)orderMessage fromScheme:self.appSchemeDic[ALIPAYFLAG] callback:^(NSDictionary *resultDic) {
            NSString *resultStatus = resultDic[@"resultStatus"];
            NSString *resultMessage = resultDic[@"memo"];
            PayResult resultCode = PayResultSuccess;
            switch (resultStatus.integerValue) {
                case 9000: // 成功
                    resultCode = PayResultSuccess;
                    break;
                case 6001: // 取消
                    resultCode = PayResultCancel;
                    break;
                default:
                    resultCode = PayResultFailure;
                    break;
            }
            if (self.callBack) {
                self.callBack(resultCode, resultMessage);
            }
        }];
    } else if (payType == PayTypeUnion) {
        BOOL flag = [[UPPaymentControl defaultControl] startPay:(NSString *)orderMessage fromScheme:self.appSchemeDic[UNIONPAYFLAG] mode:unionMode viewController:sourceVC];
        if (!flag) {
            if (self.callBack) {
                self.callBack(PayResultFailure, @"银联发送支付请求失败");
            }
        }
    }
}

- (BOOL)handleUrl:(NSURL *)url {
    if ([url.host isEqualToString:@"pay"]) { // 微信
        return [WXApi handleOpenURL:url delegate:self];
    } else if ([url.host isEqualToString:@"safepay"]) { // 支付宝
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSString *resultStatus = resultDic[@"resultStatus"];
            NSString *resultMessage = resultDic[@"memo"];
            PayResult resultCode = PayResultSuccess;
            switch (resultStatus.integerValue) {
                case 9000: // 成功
                    resultCode = PayResultSuccess;
                    break;
                case 6001: // 取消
                    resultCode = PayResultCancel;
                    break;
                default:
                    resultCode = PayResultFailure;
                    break;
            }
            if (self.callBack) {
                self.callBack(resultCode, resultMessage);
            }
        }];
        return YES;
    } else if ([url.host hasPrefix:@"uppayresult"]) { // 银联
        [[UPPaymentControl defaultControl] handlePaymentResult:url completeBlock:^(NSString *code, NSDictionary *data) {
            PayResult resultCode = PayResultSuccess;
            NSString *resultMessage = @"订单支付成功";
            if ([code isEqualToString:@"success"]) {
                resultCode = PayResultSuccess;
                resultMessage = @"订单支付成功";
            } else if ([code isEqualToString:@"fail"]) {
                resultCode = PayResultFailure;
                resultMessage = @"订单支付失败";
            } else if ([code isEqualToString:@"cancel"]) {
                resultCode = PayResultCancel;
                resultMessage = @"用户中途取消";
            } else {
                resultCode = PayResultFailure;
                resultMessage = @"未知错误";
            }
            if (self.callBack) {
                self.callBack(resultCode, resultMessage);
            }
        }];
        return YES;
    }
    return NO;
}

#pragma mark - delegate

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResult resultCode = PayResultSuccess;
        NSString *resultMessage = resp.errStr;
        switch (resp.errCode) {
            case 0:
                resultCode = PayResultSuccess;
                resultMessage = @"订单支付成功";
                break;
            case -1:
                resultCode = PayResultFailure;
                resultMessage = resp.errStr;
                break;
            case -2:
                resultCode = PayResultCancel;
                resultMessage = @"用户中途取消";
                break;
            default:
                resultCode = PayResultFailure;
                resultMessage = resp.errStr;
                break;
        }
        if (self.callBack) {
            self.callBack(resultCode, resultMessage);
        }
    }
}

#pragma mark - lazy load

- (NSMutableDictionary *)appSchemeDic {
    if (_appSchemeDic == nil) {
        _appSchemeDic = [NSMutableDictionary dictionary];
    }
    return _appSchemeDic;
}

@end
